<template>
  <!--考核部门维护-->
  <div class="full-size">
    <BasicTable @register="registerTable">
      <!--插槽:table标题-->
      <template #tableTitle>
        <!-- <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 添加考核部门</a-button> -->
        <a-button preIcon="ant-design:edit-outlined" @click="batchEdit" v-if="!startEdit"> 批量编辑</a-button>
        <a-button type="primary" preIcon="ant-design:save-outlined" @click="batchSave" v-if="startEdit"> 保存</a-button>
        <a-button preIcon="ant-design:close-outlined" @click="editCancel" v-if="startEdit"> 取消</a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.editComponent == 'InputNumber'">
          <a-input-number v-model:value="record[column['dataIndex']]" v-if="startEdit" style="width: 100%" size="small" />
          <span v-else :title="text">
            {{ text }}
          </span>
        </template>
        <template v-if="column.editComponent == 'Switch'">
          <a-switch checkedChildren="是" unCheckedChildren="否" :checkedValue="'true'" :unCheckedValue="'false'" :disabled="!startEdit" size="small" v-model:checked="record[column['dataIndex']]" />
        </template>
        <!-- <template v-if="column.dataIndex === 'orgType' && startEdit">
          <a-select
            v-model:value="record.orgType"
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择"
            :fieldNames="{ label: 'text', value: 'value' }"
            :options="orgData"
            allow-clear
          />
        </template> -->
        <template v-if="column.dataIndex === 'isIntensification'">
          <a-switch checkedChildren="是" unCheckedChildren="否" :checkedValue="'true'" :unCheckedValue="'false'" :disabled="true" size="small" v-model:checked="record[column['dataIndex']]" />
        </template>
        <template v-if="column.dataIndex === 'orgType'">
          <a-select :options="orgData" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{
              label: 'text',
              value: 'value',
            }" />
        </template>
        <template v-if="column.dataIndex === 'analysisType'">
          <a-select :options="analysisTypeList" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{
              label: 'name',
              value: 'id',
            }" />
        </template>
        <template v-if="column.dataIndex === 'psnNum'">
          <span v-if="!startEdit">
            {{ record.psnName }}
          </span>
          <a-select v-else v-model:value="record.psnCode" style="width: 100%" placeholder="请选择" :open="false" :disabled="disabled" allow-clear :fieldNames="{ label: 'pluraName', value: 'pluraCode' }" :options="record.psnOptions" @click="showChooseModal(record, record.psnCode, 'psnNum', true)" />
        </template>
        <template v-if="column.dataIndex === 'pluraList'">
          <span v-if="!startEdit">
            {{ record.pluraNameList }}
          </span>
          <a-select v-else v-model:value="record.pluraCode" style="width: 100%" placeholder="请选择" :open="false" :disabled="disabled" allow-clear :fieldNames="{ label: 'pluraName', value: 'pluraCode' }" :options="record.pluraOptions" @click="showChooseModal(record, record.pluraCode, 'plura', true)" />
          <!-- <ZSelectCustom
            v-else
            v-model:value="record.pluraList"
            :sync="true"
            :queryApi="selectPersonTreeList"
            titleKey="title"
            rowKey="psnNum"
            :multiple="true"
            modalTitle="人员选择"
            :params="{ type: '1' }"
          /> -->
        </template>
        <template v-if="column.dataIndex === 'epmPerson1Name'">
          <span v-if="!startEdit" :title="record.epmPerson1Name">
            {{ record.epmPerson1Name }}
          </span>
          <a-select v-else v-model:value="record.epmPerson1Code" style="width: 100%" placeholder="请选择" :open="false" :disabled="disabled" allow-clear mode="multiple" :fieldNames="{ label: 'pluraName', value: 'pluraCode' }" :options="record.epmPerson1Options" @click="showChooseModal(record, record.epmPerson1Code, 'epmPerson1', false)" />
        </template>
        <template v-if="column.dataIndex === 'epmPerson2Name'">
          <span v-if="!startEdit" :title="record.epmPerson2Name">
            {{ record.epmPerson2Name }}
          </span>
          <a-select v-else v-model:value="record.epmPerson2Code" style="width: 100%" placeholder="请选择" :open="false" :disabled="disabled" allow-clear mode="multiple" :fieldNames="{ label: 'pluraName', value: 'pluraCode' }" :options="record.epmPerson2Options" @click="showChooseModal(record, record.epmPerson2Code, 'epmPerson2', false)" />
        </template>
        <template v-if="column.dataIndex === 'epmPerson3Name'">
          <span v-if="!startEdit" :title="record.epmPerson3Name">
            {{ record.epmPerson3Name }}
          </span>
          <a-select v-else v-model:value="record.epmPerson3Code" style="width: 100%" placeholder="请选择" :open="false" :disabled="disabled" allow-clear mode="multiple" :fieldNames="{ label: 'pluraName', value: 'pluraCode' }" :options="record.epmPerson3Options" @click="showChooseModal(record, record.epmPerson3Code, 'epmPerson3', false)" />
        </template>
      </template>
    </BasicTable>
  </div>
  <!-- <depart-modal @register="registerModal" @success="handleSuccess" /> -->
  <edit-modal @register="registerEditModal" @success="handleSuccess" :userData="userData" />
  <person-modal @register="registerPersonModal" @success="handlePersonSuccess" />
</template>

<script name="system-user" setup>
  //ts语法
  import ZSelectCustom from '../../../components/zSelectCustom/ZSelectCustom.vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { useModal } from '/@/components/Modal';
  // import DepartModal from './departModal.vue';
  import EditModal from './editModal.vue';
  import PersonModal from './PersonModal.vue';
  import { searchFormSchema } from './assessDepartment.data';
  import { batchUpdate, list, getAsynKeyUser, anaysisList, selectPersonTreeList } from './service';
  import { render } from '/@/utils/common/renderUtils';
  import { initDictOptions } from '/@/utils/dict/index';
  // import ZSelectDeptUser from '../../../components/selectUser/ZSelectDeptUser.vue';

  let userData = ref([]);
  let orgData = ref([]);
  const currentRecord = ref({});
  const personType = ref('');
  const analysisTypeList = ref([]);
  anaysisList().then((res) => {
    analysisTypeList.value = res || [];
  });

  const setTreeData = (list, id, data) => {
    list.forEach((l) => {
      if (l.id == id) {
        l.children = [...data];
      }
      if (l.children) {
        setTreeData(l.children, id, data);
      }
    });
  };

  // @ts-ignore
  getAsynKeyUser().then(async (res) => {
    userData.value = res;
  });

  const loadUserData = (treeNode) => {
    return new Promise((resolve) => {
      const { id } = treeNode.dataRef;
      getAsynKeyUser({ parentId: id }).then((res) => {
        resolve(res);
        setTreeData(userData.value, id, res);
      });
    });
  };
  initDictOptions('hub_org_type').then((res) => {
    orgData.value = res || [];
  });

  let spinning = ref(false);
  let startEdit = ref(false);
  //注册新增弹窗
  const [registerModal, { openModal: openModal = () => {} }] = useModal();
  //注册编辑弹窗
  const [registerEditModal, { openModal: openEditModal = () => {} }] = useModal();
  //批量编辑选人弹框
  const [registerPersonModal, { openModal: openPersonModal = () => {} }] = useModal();

  let tableColumns = [
    {
      title: 'id',
      dataIndex: 'id',
      width: 80,
      ifShow: false,
    },
    {
      title: '部门名称',
      dataIndex: 'orgName',
      width: 200,
      align: 'center',
      fixed: 'left',
    },
    {
      title: '部门编码',
      dataIndex: 'orgCode',
      width: 140,
      align: 'center',
      // fixed: 'left',
    },
    {
      title: '上级部门',
      dataIndex: 'parentOrgName',
      width: 200,
      align: 'center',
    },
    {
      title: '适用考核单位',
      dataIndex: 'suitUnitName',
      width: 200,
      align: 'center',
    },
    {
      title: '组织类型',
      dataIndex: 'orgType',
      width: 200,
      align: 'center',
      customRender: ({ text }) => {
        // console.log("2",render.renderDict(text, 'org_type'))
        return render.renderDict(text, 'hub_org_type');
      },
    },
    {
      title: '分析类型',
      dataIndex: 'analysisType',
      width: 200,
      align: 'center',
      customRender: ({ text }) => {
        let desc = analysisTypeList.value.filter((item) => item.id === text)[0]?.name;
        return desc;
      },
    },

    {
      title: '是否考核',
      dataIndex: 'assess',
      width: 100,
      align: 'center',
      editComponent: 'Switch',
    },
    {
      title: '是否集约化',
      dataIndex: 'isIntensification',
      width: 100,
      align: 'center',
    },
    {
      title: '绩效员',
      dataIndex: 'pluraList',
      width: 240,
      align: 'center',
    },
    {
      title: '部门负责人',
      dataIndex: 'psnNum',
      width: 240,
      align: 'center',
    },
    {
      title: '分管领导',
      dataIndex: 'epmPerson1Name',
      width: 200,
      align: 'center',
    },
    {
      title: '主要领导',
      dataIndex: 'epmPerson2Name',
      width: 200,
      align: 'center',
    },
    {
      title: '其它分管领导',
      dataIndex: 'epmPerson3Name',
      width: 200,
      align: 'center',
    },
    {
      title: '排序',
      dataIndex: 'displayOrder',
      editComponent: 'InputNumber',
      align: 'center',
      width: 100,
    },
  ];

  // 列表页面公共参数、方法
  const { tableContext } = useListPage({
    designScope: 'user-list',
    spinning: () => (spinning.value = !spinning.value),
    tableProps: {
      api: list,
      columns: tableColumns,
      size: 'small',
      formConfig: {
        // labelWidth: 200,
        schemas: searchFormSchema,
      },
      actionColumn: {
        width: 100,
        fixed: 'right',
      },
    },
  });
  //注册table数据
  // eslint-disable-next-line @typescript-eslint/no-unused-vars,no-unused-vars
  const [registerTable, { getForm = () => {}, reload = () => {}, updateTableDataRecord, getDataSource, setColumns, setTableData }] = tableContext;

  /**
   * 新增事件
   */
  function handleCreate() {
    openModal(true, {});
  }
  /**
   * 编辑事件
   */
  async function handleEdit(record) {
    let data = startEdit.value ? record : handleEditData(record);
    console.log('编辑', data);
    openEditModal(true, {
      record: data,
    });
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    startEdit.value = false;
    reload();
  }
  //选人确定回调
  function handlePersonSuccess(data) {
    console.log(data);
    switch (personType.value) {
      case 'plura':
        currentRecord.value.pluraCode = data.checkedKeys.value;
        currentRecord.value.pluraOptions = [data.recordRows.value];
        currentRecord.value.pluraList = data.checkedKeys.value.toString();
        break;
      case 'psnNum':
        currentRecord.value.psnCode = data.checkedKeys.value;
        currentRecord.value.psnOptions = [data.recordRows.value];
        currentRecord.value.psnNum = data.checkedKeys.value.toString();
        break;
      default:
        currentRecord.value[personType.value + 'Code'] = data.checkedKeys.value;
        currentRecord.value[personType.value + 'Options'] = data.recordRows.value;
        currentRecord.value[personType.value] = data.checkedKeys.value.toString();
        break;
    }
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      },
    ];
  }

  /**
   * author:lhw
   * description: 批量编辑方法
   * @params: @
   * date: 2023/2/13
   * lastModify: 2023/2/13
   */
  function batchEdit() {
    setData();
    startEdit.value = true;
  }
  const handleEditData = (record) => {
    record.pluraOptions = [{ pluraCode: record.pluraList, pluraName: record.pluraNameList }];
    record.pluraCode = record.pluraList ? record.pluraList.split(',') : [];
    record.psnOptions = [{ pluraCode: record.psnNum, pluraName: record.psnName }];
    record.psnCode = record.psnNum ? record.psnNum.split(',') : [];
    setDataOptions(record, 'epmPerson1');
    setDataOptions(record, 'epmPerson2');
    setDataOptions(record, 'epmPerson3');
    return record;
  };
  //处理数据
  function setData() {
    let tableData = getDataSource();
    tableData.forEach((item) => {
      item.pluraOptions = [{ pluraCode: item.pluraList, pluraName: item.pluraNameList }];
      item.pluraCode = item.pluraList?.split(',') || [];
      item.psnOptions = [{ pluraCode: item.psnNum, pluraName: item.psnName }];
      item.psnCode = item.psnNum?.split(',') || [];
      setDataOptions(item, 'epmPerson1');
      setDataOptions(item, 'epmPerson2');
      setDataOptions(item, 'epmPerson3');
    });
    console.log('tableData-batchEdit', tableData);
  }
  //处理数据 设施options
  function setDataOptions(record, label) {
    record[label + 'Code'] = record[label] ? record[label].split(',') : [];
    record[label + 'NameList'] = record[label + 'Name'] ? record[label + 'Name'].split(',') : [];
    if (record[label + 'Code'].length > 0) {
      record[label + 'Options'] = record[label + 'Code'].map((i, index) => {
        return { pluraName: record[label + 'NameList'][index], pluraCode: i };
      });
    } else {
      record[label + 'Options'] = [];
    }
  }

  /**
   * author:lhw
   * description: 批量编辑保存
   * @params: @
   * date: 2023/2/13
   * lastModify: 2023/2/13
   */
  function batchSave() {
    console.log('表格数据', getDataSource());
    getDataSource().forEach((item) => {
      if (!item.pluraCode || item.pluraCode?.length == 0) {
        item.pluraList = '';
        item.pluraNameList = '';
      }
      if (!item.psnCode || item.psnCode?.length == 0) {
        item.psnNum = '';
        item.psnName = '';
      }
      if (!item.epmPerson1Code || item.epmPerson1Code?.length == 0) {
        item.epmPerson1 = '';
        item.epmPerson1Name = '';
      }
      if (!item.epmPerson2Code || item.epmPerson2Code?.length == 0) {
        item.epmPerson2 = '';
        item.epmPerson2Name = '';
      }
      if (!item.epmPerson3Code || item.epmPerson3Code?.length == 0) {
        item.epmPerson3 = '';
        item.epmPerson3Name = '';
      }
      delete item.pluraOptions;
      delete item.psnOptions;
      delete item.epmPerson1Options;
      delete item.epmPerson2Options;
      delete item.epmPerson3Options;
      item.epmPerson1 = item.epmPerson1Code.toString();
      item.epmPerson2 = item.epmPerson2Code.toString();
      item.epmPerson3 = item.epmPerson3Code.toString();
    });
    batchUpdate(getDataSource()).then(() => {
      reload();
      startEdit.value = false;
    }); //保存数据
  }
  //选人弹框
  function showChooseModal(record, list, type, isOnly) {
    currentRecord.value = record;
    personType.value = type;
    openPersonModal(true, { list, isOnly });
  }

  /**
   * author:lhw
   * description: 取消批量编辑
   * @params: @
   * date: 2023/2/13
   * lastModify: 2023/2/13
   */
  async function editCancel() {
    startEdit.value = false;
    let records = getDataSource();
    for (const r of records) {
      try {
        await r.onEdit(false, false);
      } catch (e) {}
    }
    reload();
  }
</script>
<style lang="less" scoped>
  /deep/.ant-table-wrapper {
    padding: 16px !important;
  }
  .full-size {
    width: 100%;
    height: 100%;
  }
  /deep/.ant-select-selection-item-remove {
    display: none !important;
  }
</style>
